import React, { useState, useEffect, useCallback } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from './ui/card';
import { Button } from './ui/button';
import { Progress } from './ui/progress';
import { Badge } from './ui/badge';
import { Brain, Timer, Target, RotateCcw, Eye, EyeOff } from 'lucide-react';
import { TestResult } from '../types';
import { MemoryTestState, GridItem } from '../types/memoryTest';
import { MemoryTestGrid } from './MemoryTestGrid';
import { MEMORY_TEST_CONFIG } from '../constants/memoryTest';
import {
  generateSequence,
  calculateMemorizeTime,
  createInitialGrid,
  calculateLevelScore,
  calculateAverageScore,
  calculateFinalScore,
  getRating,
  updateGridWithCorrectness,
  shouldCompleteTest,
  createTestResult
} from '../utils/memoryTest';

interface MemoryTestProps {
  onComplete: (result: TestResult) => void;
}

export function MemoryTest({ onComplete }: MemoryTestProps) {
  const [state, setState] = useState<MemoryTestState>('ready');
  const [currentLevel, setCurrentLevel] = useState(1);
  const [grid, setGrid] = useState<GridItem[]>([]);
  const [sequence, setSequence] = useState<number[]>([]);
  const [userSequence, setUserSequence] = useState<number[]>([]);
  const [memorizeTime, setMemorizeTime] = useState(3);
  const [displayTime, setDisplayTime] = useState(3);
  const [scores, setScores] = useState<number[]>([]);
  const [showSequence, setShowSequence] = useState(false);
  const [testStartTime, setTestStartTime] = useState<number>(0);

  const generateLevel = useCallback(() => {
    const newGrid = createInitialGrid();
    const newSequence = generateSequence(currentLevel);
    const timeNeeded = calculateMemorizeTime(currentLevel);
    
    setSequence(newSequence);
    setGrid(newGrid);
    setUserSequence([]);
    setMemorizeTime(timeNeeded);
    setDisplayTime(timeNeeded);
  }, [currentLevel]);

  const startLevel = useCallback(() => {
    generateLevel();
    setState('memorize');
    setShowSequence(true);
    setTestStartTime(Date.now());

    setTimeout(() => {
      setShowSequence(false);
      setState('recall');
    }, memorizeTime * 1000);
  }, [generateLevel, memorizeTime]);

  const handleCellClick = (cellId: number) => {
    if (state !== 'recall') return;

    const newUserSequence = [...userSequence, cellId];
    setUserSequence(newUserSequence);

    setGrid(prev => prev.map(cell => 
      cell.id === cellId 
        ? { ...cell, isSelected: true }
        : cell
    ));

    if (newUserSequence.length === sequence.length) {
      const finalScore = calculateLevelScore(newUserSequence, sequence);
      setScores(prev => [...prev, finalScore]);

      setGrid(prev => updateGridWithCorrectness(prev, newUserSequence, sequence));

      setTimeout(() => {
        if (shouldCompleteTest(currentLevel, finalScore)) {
          setState('complete');
        } else {
          setCurrentLevel(prev => prev + 1);
          setState('ready');
        }
      }, MEMORY_TEST_CONFIG.SEQUENCE_COMPLETION_DELAY);
    }
  };

  const resetTest = () => {
    setState('ready');
    setCurrentLevel(1);
    setGrid([]);
    setSequence([]);
    setUserSequence([]);
    setScores([]);
    setShowSequence(false);
    setTestStartTime(0);
    setMemorizeTime(3);
    setDisplayTime(3);
  };

  const handleComplete = () => {
    const result = createTestResult(scores, currentLevel, testStartTime, memorizeTime);
    onComplete(result);
  };

  useEffect(() => {
    let interval: NodeJS.Timeout;
    
    if (state === 'memorize') {
      interval = setInterval(() => {
        setDisplayTime(prev => {
          if (prev <= 1) {
            clearInterval(interval);
            return 0;
          }
          return prev - 1;
        });
      }, 1000);
    } else {
      setDisplayTime(memorizeTime);
    }

    return () => {
      if (interval) clearInterval(interval);
    };
  }, [state, memorizeTime]);

  if (state === 'complete') {
    const rating = getRating(calculateFinalScore(scores, currentLevel));
    
    return (
      <div className="max-w-2xl mx-auto space-y-6">
        <Card>
          <CardHeader className="text-center">
            <CardTitle className="flex items-center justify-center gap-2">
              <Brain className="w-6 h-6 text-purple-500" />
              测试完成！
            </CardTitle>
          </CardHeader>
          <CardContent className="space-y-6">
            <div className="text-center space-y-4">
              <div className="text-6xl font-bold text-primary">
                {calculateFinalScore(scores, currentLevel)}
              </div>
              <div className={`text-xl font-semibold ${rating.color}`}>
                {rating.text}
              </div>
              <div className="text-lg">
                完成关卡: <span className="font-bold text-primary">{currentLevel - 1}</span>
              </div>
            </div>

            <div className="grid grid-cols-2 gap-4">
              <div className="text-center p-4 bg-muted rounded-lg">
                <div className="text-2xl font-bold">{currentLevel - 1}</div>
                <div className="text-sm text-muted-foreground">完成关卡</div>
              </div>
              <div className="text-center p-4 bg-muted rounded-lg">
                <div className="text-2xl font-bold">{calculateAverageScore(scores)}%</div>
                <div className="text-sm text-muted-foreground">平均准确率</div>
              </div>
            </div>

            <div className="space-y-2">
              <h3 className="font-semibold">各关成绩</h3>
              <div className="grid grid-cols-4 gap-2">
                {scores.map((score, index) => (
                  <div key={index} className="text-center p-2 bg-muted rounded">
                    <div className="font-semibold">{score}%</div>
                    <div className="text-xs text-muted-foreground">第{index + 1}关</div>
                  </div>
                ))}
              </div>
            </div>

            <div className="flex gap-4">
              <Button 
                onClick={resetTest} 
                variant="outline" 
                className="flex-1 border-2 border-slate-300 hover:border-purple-500 hover:bg-purple-50 hover:text-purple-700 transition-all duration-200"
              >
                <RotateCcw className="w-4 h-4 mr-2" />
                重新测试
              </Button>
              <Button 
                onClick={handleComplete} 
                className="flex-1 bg-gradient-to-r from-purple-500 to-pink-500 text-white hover:from-purple-600 hover:to-pink-600 shadow-md hover:shadow-lg transition-all duration-200"
              >
                保存结果
              </Button>
            </div>
          </CardContent>
        </Card>
      </div>
    );
  }

  return (
    <div className="max-w-2xl mx-auto space-y-6">
      <Card>
        <CardContent className="pt-6">
          <div className="flex justify-between items-center mb-2">
            <span className="text-sm">关卡进度</span>
            <span className="text-sm">{currentLevel}/{MEMORY_TEST_CONFIG.MAX_LEVELS}</span>
          </div>
          <Progress value={(currentLevel / MEMORY_TEST_CONFIG.MAX_LEVELS) * 100} />
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <CardTitle className="flex items-center justify-between">
            <div className="flex items-center gap-2">
              <Brain className="w-5 h-5 text-purple-500" />
              记忆力测试 - 第 {currentLevel} 关
            </div>
            {state === 'memorize' && (
              <Badge variant="secondary" className="flex items-center gap-1">
                <Timer className="w-3 h-3" />
                {displayTime}秒
              </Badge>
            )}
          </CardTitle>
        </CardHeader>
        <CardContent className="space-y-6">
          {state === 'ready' && (
            <div className="text-center space-y-6">
              <div>
                <h2 className="text-xl font-bold mb-2">第 {currentLevel} 关</h2>
                <p className="text-muted-foreground mb-4">
                  记住高亮方块的位置，然后按相同顺序点击
                </p>
                <div className="flex justify-center gap-4">
                  <Badge variant="outline">
                    {currentLevel + 2} 个方块
                  </Badge>
                  <Badge variant="outline">
                    {calculateMemorizeTime(currentLevel)} 秒记忆时间
                  </Badge>
                </div>
              </div>
              <Button 
                size="lg" 
                onClick={startLevel}
                className="bg-gradient-to-r from-slate-400 to-gray-500 hover:from-slate-500 hover:to-gray-600 text-white shadow-lg hover:shadow-xl transform hover:scale-105 transition-all duration-300 border-0 min-w-[140px] h-12"
              >
                <Brain className="w-5 h-5 mr-2" />
                开始第 {currentLevel} 关
              </Button>
            </div>
          )}

          {(state === 'memorize' || state === 'recall') && (
            <div className="space-y-4">
              <div className="text-center">
                <div className="flex items-center justify-center gap-4 mb-4">
                  {state === 'memorize' ? (
                    <>
                      <Eye className="w-5 h-5 text-blue-500" />
                      <span>记住高亮的方块位置</span>
                    </>
                  ) : (
                    <>
                      <EyeOff className="w-5 h-5 text-green-500" />
                      <span>按顺序点击方块 ({userSequence.length}/{sequence.length})</span>
                    </>
                  )}
                </div>
              </div>

              <MemoryTestGrid
                grid={grid}
                sequence={sequence}
                showSequence={showSequence}
                onCellClick={handleCellClick}
                isInteractive={state === 'recall'}
              />

              {state === 'recall' && userSequence.length === sequence.length && (
                <div className="text-center p-4 bg-muted rounded-lg">
                  <p className="font-semibold">
                    {userSequence.every((id, index) => id === sequence[index]) 
                      ? "完美！正在进入下一关..." 
                      : "部分正确，正在进入下一关..."}
                  </p>
                </div>
              )}
            </div>
          )}
        </CardContent>
      </Card>

      {scores.length > 0 && (
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Target className="w-5 h-5" />
              当前成绩
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="grid grid-cols-3 gap-4 text-center">
              <div>
                <div className="text-2xl font-bold">{calculateAverageScore(scores)}%</div>
                <div className="text-sm text-muted-foreground">平均准确率</div>
              </div>
              <div>
                <div className="text-2xl font-bold">{currentLevel - 1}</div>
                <div className="text-sm text-muted-foreground">完成关卡</div>
              </div>
              <div>
                <div className="text-2xl font-bold">{scores[scores.length - 1] || 0}%</div>
                <div className="text-sm text-muted-foreground">上一关</div>
              </div>
            </div>
          </CardContent>
        </Card>
      )}

      <Card>
        <CardContent className="pt-6">
          <h3 className="font-semibold mb-2">测试说明</h3>
          <ul className="text-sm text-muted-foreground space-y-1">
            <li>• 记住高亮方块的位置和顺序</li>
            <li>• 记忆时间结束后，按相同顺序点击方块</li>
            <li>• 每关难度递增，需要记住更多方块</li>
            <li>• 准确率低于50%将结束测试</li>
            <li>• 数字表示点击的顺序</li>
          </ul>
        </CardContent>
      </Card>
    </div>
  );
}